package com.topway.dsmflex.dao.synchro;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.topway.dsmflex.model.synchro.DataColumnBean;
import com.topway.dsmflex.model.synchro.DataSourceBean;


/**
 * 
 * @author liusy 2013-05-8
 *
 */
public class SqlDao extends TableDao{
	
	private final String pageSql = "SELECT * FROM ( SELECT A.*, ROWNUM RN FROM ( #liusyPage# ) A WHERE ROWNUM <= 1 ) WHERE RN >= 0";
	
	
	private static Logger log = Logger.getLogger(TableDao.class);
	
	private static ThreadLocal<SqlDao> sqlDao= new ThreadLocal<SqlDao>();
	
	public SqlDao(){}
	
	
	public synchronized static SqlDao getSqlDao()
	{
		if(null==sqlDao.get())
		{
			sqlDao.set(new SqlDao());
		}
		return sqlDao.get();
	}
	
	@Override
	public List<DataColumnBean> getColumnInfo(DataSourceBean  _daSource,String sql) throws SQLException
	{
		this.getConnection(_daSource);
		List<DataColumnBean> list = new ArrayList<DataColumnBean>();
		List<String> listStr = new ArrayList<String>();
		listStr.add("");
		Statement stmt = null;
		ResultSet rs  = null;
		try {
			stmt =conn.createStatement();
			if(_daSource.getDriver().toLowerCase().indexOf("mysql")!=-1)
				rs =stmt.executeQuery( sql+"limit 0,1");
			else
				rs =stmt.executeQuery(pageSql.replace("#liusyPage#", sql));
			  ResultSetMetaData rsmd = rs.getMetaData();
			  int count = rsmd.getColumnCount();
				if(_daSource.getDriver().toLowerCase().indexOf("mysql")==-1)
					count=count-1;
		     
		  	DataColumnBean dc = null;
		      for (int k = 0; k < count; k++) {
		 		dc = new DataColumnBean(rsmd.getColumnName(k + 1).toUpperCase());
				listStr.add(dc.getColumnNameSource());
				list.add(dc);
		      }
		  	sourceColumn = new String[list.size()];
			listStr.toArray(sourceColumn);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}finally{
			if(null!=rs)
				rs.close();
			if(null!=stmt)
				stmt.close();
		}
		return list;
	
	}
	

}
